package com.htandroid.htandroid.aty;

/**
 * Created by Administrator on 2015/12/26.
 */

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.soap.AbSoapUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.ioc.AbIocView;
import com.ab.view.titlebar.AbTitleBar;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.entity.GcwxList;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.htandroid.sys.Basenvo;
import com.htandroid.htandroid.sys.InstorageURL;
import com.htandroid.htandroid.sys.User;
import com.htandroid.htandroid.webservice.BuildGcwxXMLService;
import com.htandroid.htandroid.webservice.XMLGcwxVouchlist;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

public class Gcwx_lr_detail extends AbActivity {
    public MyApplication myApplication;
    private GcwxList vouch;
    private ArrayList<GcwxList> vouchlist;
    private String initTime = "", ismulpoint = "0";
    private int icurrentrow;
    private String ctype = "add";

    private AbTitleBar mAbTitleBar = null;
    private View rightView1 = null;
    private View rightView2 = null;
    private View rightView3 = null;
    private View rightView4 = null;
    private TextView tv_currentrow;
    //private AbLoadDialogFragment mDialogFragment = null;
    private String mFilePath = "";
    private ImageView img_camera;

    @AbIocView(id = R.id.btn1_tv, click = "btnClick")
    TextView btn1_tv;
    @AbIocView(id = R.id.btn2_tv, click = "btnClick")
    TextView btn2_tv;
    @AbIocView(id = R.id.ddate_tv)
    TextView ddate_tv;
    @AbIocView(id = R.id.cdepname_tv)
    TextView cdepname_tv;
    @AbIocView(id = R.id.cvouchid_tv)
    TextView cvouchid_tv;
    @AbIocView(id = R.id.ctypename_tv)
    TextView ctypename_tv;
    @AbIocView(id = R.id.cwxplname_tv)
    TextView cwxplname_tv;
    @AbIocView(id = R.id.cdjname_tv)
    TextView cdjname_tv;
    @AbIocView(id = R.id.cwxtypename_tv)
    TextView cwxtypename_tv;
    @AbIocView(id = R.id.printsend_tv)
    TextView printsend_tv;
    @AbIocView(id = R.id.cbxtext_et)
    EditText cbxtext_et;
    @AbIocView(id = R.id.cdepname_iv)
    ImageView cdepname_iv;
    @AbIocView(id = R.id.cwxplname_iv)
    ImageView cwxplname_iv;
    @AbIocView(id = R.id.cdjname_iv)
    ImageView cdjname_iv;
    @AbIocView(id = R.id.printsend_iv)
    ImageView printsend_iv;
    @AbIocView(id = R.id.planvouchid_tv)
    TextView planvouchid_tv;
    @AbIocView(id = R.id.plandate_tv)
    TextView plandate_tv;
    @AbIocView(id = R.id.cmaker_tv)
    TextView cmaker_tv;

    ImageView ivShowPicture;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.layout_gcwx_lr_detail);
        initview();
    }

    public void btnClick(View v) {
        switch (v.getId()) {
            case R.id.btn1_tv:
                btn1_click(v);
                break;
            case R.id.btn2_tv:
                btn2_click(v);
                break;
        }
    }

    //初始化
    private void initview() {
        myApplication = (MyApplication) abApplication;//获得我们的应用程序全局变量
        mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText("部门报修");
        mAbTitleBar.setLogo(R.drawable.icon_back);
        mAbTitleBar.getLogoView().setLayoutParams(new LinearLayout.LayoutParams(58, 57));
        mAbTitleBar.getLogoView().setFocusable(true);
        mAbTitleBar.getLogoView().setFocusableInTouchMode(true);
        mAbTitleBar.getLogoView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("currentrow", icurrentrow);//把当前行返回到上一页面,方便更换上一页面的选中行
                setResult(R.layout.basenvo_nofunc / 300000, intent);  //设置返回结果
                //返回时增加提示,防止误点
                finish();
            }
        });
        mAbTitleBar.setTitleBarBackground(R.color.common_title);
        mAbTitleBar.setTitlePadding(118, 0, 0, 0);

        mAbTitleBar.clearRightView();
        rightView1 = mInflater.inflate(R.layout.btn_abs_back, null);
        mAbTitleBar.addRightView(rightView1);
        rightView2 = mInflater.inflate(R.layout.tv_currentrow, null);
        mAbTitleBar.addRightView(rightView2);
        rightView3 = mInflater.inflate(R.layout.btn_abs_forward, null);
        mAbTitleBar.addRightView(rightView3);
        tv_currentrow = (TextView) rightView2.findViewById(R.id.tv_currentrow);

        //获取传递的对象参数
        Intent intent = getIntent();
        vouchlist = (ArrayList<GcwxList>) intent.getSerializableExtra("vouchlist");
        ctype = intent.getExtras().getString("ctype");
        icurrentrow = getIntent().getExtras().getInt("currentrow");
        ismulpoint = getIntent().getExtras().getString("ismulpoint");

        //新增时隐藏切换图标
        if (ctype.equals("add")) {
//            rightView1.setVisibility(View.GONE);
//            rightView2.setVisibility(View.GONE);
//            rightView3.setVisibility(View.GONE);
            ivShowPicture = (ImageView) findViewById(R.id.ivShowPicture);
            mFilePath = Environment.getExternalStorageDirectory().getPath();// 获取SD卡路径
            mFilePath = mFilePath + "/" + "temp.png";// 指定路径
            mAbTitleBar.clearRightView();
            rightView4 = mInflater.inflate(R.layout.btn_camera, null);
            mAbTitleBar.addRightView(rightView4);
            mAbTitleBar.setTitlePadding(0, 0, 0, 0);
            rightView4.setPadding(0, 0, 0, 0);
            img_camera = (ImageView) rightView4.findViewById(R.id.img_camera);
            img_camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    scancode_click();
                }
            });
        }
        insert_data(icurrentrow);
    }

    //调用照相机扫描
    public void scancode_click() {
//        Intent intent = new Intent();
//        intent.setClass(getApplicationContext(), Basenvo_Capture.class);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        Bundle bundle = new Bundle();
//        bundle.putInt("cameratype", 0);
//        bundle.putString("title","gcwx_lr");
//        intent.putExtras(bundle);
//        startActivityForResult(intent, 1);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 启动系统相机
        Uri photoUri = Uri.fromFile(new File(mFilePath)); // 传递路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);// 更改系统默认存储路径
        startActivityForResult(intent, 1);
    }

    //为窗口填充数据
    public void insert_data(int row) {
        if (ctype.equals("add")) {
            vouch = new GcwxList();
            vouch.init();
        } else {
            vouch = vouchlist.get(row);
        }
        icurrentrow = row;
        tv_currentrow.setText((icurrentrow + 1) + "/" + (vouchlist.size()));
        //新增时,只显示需要编辑的行
        if (ctype.equals("add")) {
            LinearLayout cvouchid_ll = (LinearLayout) findViewById(R.id.cvouchid_ll);
            cvouchid_ll.setVisibility(View.GONE);
            LinearLayout planvouchid_ll = (LinearLayout) findViewById(R.id.planvouchid_ll);
            planvouchid_ll.setVisibility(View.GONE);
            LinearLayout plandata_ll = (LinearLayout) findViewById(R.id.plandata_ll);
            plandata_ll.setVisibility(View.GONE);
            LinearLayout cmaker_ll = (LinearLayout) findViewById(R.id.cmaker_ll);
            cmaker_ll.setVisibility(View.GONE);
        }
        showwin(true);
        //填写文本内容
        cvouchid_tv.setText(vouch.getCvouchid());
        ctypename_tv.setText(vouch.getCtypename());
        if (!vouch.getCdepcode().equals("")) {
            cdepname_tv.setText(vouch.getCdepname());
            cdepname_tv.setTag(vouch.getCdepcode());
        }

        if (!vouch.getCwxplcode().equals("")) {
            cwxplname_tv.setText(vouch.getCwxplname());
            cwxplname_tv.setTag(vouch.getCwxplcode());
        }

        if (!vouch.getCdjcode().equals("")) {
            cdjname_tv.setText(vouch.getCdjname());
            cdjname_tv.setTag(vouch.getCdjcode());
        }

        planvouchid_tv.setText(vouch.getPlanvouchid());
        plandate_tv.setText(vouch.getPlandate());
        cmaker_tv.setText(vouch.getCmaker());
        printsend_tv.setText(vouch.getPrintsendname());
        printsend_tv.setTag(vouch.getPrintsend());
        cbxtext_et.setText(vouch.getCbxtext());

        if (!vouch.getDdate().equals("")) {
            initTime = vouch.getDdate();
        } else {
            Date curDate = new Date(System.currentTimeMillis());
            initTime = Basenvo.customDateFormat("yyyy-MM-dd HH:mm", curDate);
        }
        ddate_tv.setText(initTime);
        //判断是否为新增,新增则不显示删除按钮
        if (vouch.getCmaker().equals("")) {
            //隐藏
            btn2_tv.setVisibility(View.GONE);
        }
    }

    //选择
    public void cdep_choose(View v) {
        String cdepcode = "";
        String cdepname = "";
        if (cdepname_tv.getTag() != null) {
            cdepcode = cdepname_tv.getTag().toString();
            cdepname = cdepname_tv.getText().toString();
        }
        Intent intent = new Intent(getApplicationContext(), Basenvo_Choosecdept.class);
        // 设置传递数据
        intent.putExtra("ccode", cdepcode);
        intent.putExtra("cname", cdepname);
        intent.putExtra("btntype", "cdept");
        intent.putExtra("cmsgtype", "维修单");
        startActivityForResult(intent, R.layout.basenvo_rchoose / 200000);
    }

    public void cwxpl_choose(View v) {
        String cwxplcode = "";
        if (cwxplname_tv.getTag() != null) {
            cwxplcode = cwxplname_tv.getTag().toString();
        }
        String cdepcode = "";
        if (cdepname_tv.getTag() != null) {
            cdepcode = cdepname_tv.getTag().toString();
        }
        if (cdepcode.equals("")) {
            AbToastUtil.showToastInThread(getApplicationContext(), "请先选择报修部门!");
            return;
        }
        Intent intent = new Intent(getApplicationContext(), Basenvo_Choosecwxpl.class);
        // 设置传递数据
        intent.putExtra("ccode", cwxplcode);
        intent.putExtra("cname", cdepcode);
        intent.putExtra("btntype", "cwxpl");
        startActivityForResult(intent, R.layout.basenvo_rchoose / 200000);
    }

    public void cdj_choose(View v) {
        String cdjcode = "";
        String cdjname = "";
        if (cdjname_tv.getTag() != null) {
            cdjcode = cdjname_tv.getTag().toString();
            cdjname = cdjname_tv.getText().toString();
        }
        Intent intent = new Intent(getApplicationContext(), Basenvo_Choosecwxdj.class);
        // 设置传递数据
        intent.putExtra("ccode", cdjcode);
        intent.putExtra("cname", cdjname);
        intent.putExtra("btntype", "cwxdj");
        startActivityForResult(intent, R.layout.basenvo_rchoose / 200000);
    }

    //选择
    public void printsend_choose(View v) {
        String sendname = "";
        String printname = "";
        if (printsend_tv.getTag() != null) {
            printname = printsend_tv.getTag().toString();
            sendname = printsend_tv.getText().toString();
        }

        Intent intent = new Intent(getApplicationContext(), Basenvo_Chooseprintsend.class);
        // 设置传递数据
        intent.putExtra("ccode", printname);
        intent.putExtra("cname", sendname);
        intent.putExtra("btntype", "printsend");
        startActivityForResult(intent, R.layout.basenvo_rchoose / 200000);
    }

    public void showwin(boolean stype) {
        Integer backgroundcolor = Color.TRANSPARENT;
        cbxtext_et.setEnabled(stype);
        if (stype) {
            cbxtext_et.setBackgroundResource(R.drawable.edit_background);
            cdepname_tv.setBackgroundResource(R.drawable.edit_background);
            cwxplname_tv.setBackgroundResource(R.drawable.edit_background);
            cdjname_tv.setBackgroundResource(R.drawable.edit_background);
            cwxtypename_tv.setBackgroundResource(R.drawable.edit_background);
            cbxtext_et.setBackgroundResource(R.drawable.edit_background);

            cdepname_iv.setVisibility(View.VISIBLE);
            cwxplname_iv.setVisibility(View.VISIBLE);
            cdjname_iv.setVisibility(View.VISIBLE);
            //是否多点打印
            if (!ismulpoint.equals("0")) {
                printsend_tv.setBackgroundResource(R.drawable.edit_background);
                printsend_iv.setVisibility(View.VISIBLE);
            } else {
                printsend_tv.setBackgroundColor(backgroundcolor);
                printsend_iv.setVisibility(View.GONE);
            }

        } else {
            cbxtext_et.setBackgroundColor(backgroundcolor);
            cdepname_tv.setBackgroundColor(backgroundcolor);
            cwxplname_tv.setBackgroundColor(backgroundcolor);
            cdjname_tv.setBackgroundColor(backgroundcolor);
            cwxtypename_tv.setBackgroundColor(backgroundcolor);
            cbxtext_et.setBackgroundColor(backgroundcolor);
            printsend_tv.setBackgroundColor(backgroundcolor);

            cdepname_iv.setVisibility(View.GONE);
            cwxplname_iv.setVisibility(View.GONE);
            cdjname_iv.setVisibility(View.GONE);
            printsend_iv.setVisibility(View.GONE);
        }
    }

    //维修信息保存
    public void btn1_click(View v) {
        updatedataref();
        if (!precheck()) return;
        //loadingDialog.loading(this);
        vouch.setCbxtext(cbxtext_et.getText().toString());
        vouch.setCmaker(User.nickName);
        String urlString = "http://" + InstorageURL.SERVERURL
                + BaseUrl_New;
        String[] parms = {"username", "cacc_id", "iyear"};
        String[] vals = {User.nickName, (String) myApplication.getGs_ztid(), (String) myApplication.getGs_year()};
        //生成xml
        BuildGcwxXMLService service = new BuildGcwxXMLService();
        String xmlstring = service.buildXML("gcwx_bxsave", InstorageURL.NAME_SPACE, parms, vals, "in" + String.valueOf(parms.length), vouch, null, null, null, null, null, null);
        mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "gcwx_bxsave", xmlstring, new AbSoapUtil.WebServiceCallBack() {
            @Override
            public void onSucced(String result) {
                if (result != null) {
                    //解析xml文件,返回列表
                    List<GcwxList> vouchlist = XMLGcwxVouchlist.paraseCommentInfors(result);
                    //默认显示第一行数据
                    if (vouchlist.size() > 0) {
                        vouch = vouchlist.get(0);
                    }
                    if (vouch.getSucstatus().equals("0")) {
                        AbToastUtil.showToastInThread(getApplicationContext(), "单据保存失败!");
                    } else {
                        Intent intent = new Intent();
                        setResult(R.layout.layout_gcwx_lr_detail / 100000, intent);  //设置返回结果
                        finish();
                    }
                } else {
                    AbToastUtil.showToastInThread(getApplicationContext(), "单据保存失败!数据库错误");
                }
                //loadingDialog.loadingfinish();
            }

            @Override
            public void onFailure(String result) {
                //loadingDialog.loadingfinish();
                AbToastUtil.showToastInThread(getApplicationContext(), "单据保存失败!数据库错误");
            }
        });
    }

    //维修信息删除
    public void btn2_click(View v) {
        //loadingDialog.loading(this);
        String urlString = "http://" + InstorageURL.SERVERURL
                + BaseUrl_New;
        String[] parms = {"username", "cacc_id", "iyear", "ctype"};
        String[] vals = {User.nickName, (String) myApplication.getGs_ztid(), (String) myApplication.getGs_year(), "del"};
        //生成xml
        BuildGcwxXMLService service = new BuildGcwxXMLService();
        String xmlstring = service.buildXML("gcwx_qx", InstorageURL.NAME_SPACE, parms, vals, "in" + String.valueOf(parms.length), vouch, null, null, null, null, null, null);
        mAbSoapUtil.xmlCall(urlString, InstorageURL.NAME_SPACE, "gcwx_qx", xmlstring, new AbSoapUtil.WebServiceCallBack() {
            @Override
            public void onSucced(String result) {
                if (result != null) {
                    //解析xml文件,返回列表
                    List<GcwxList> vouchlist = XMLGcwxVouchlist.paraseCommentInfors(result);
                    //默认显示第一行数据
                    if (vouchlist.size() > 0) {
                        vouch = vouchlist.get(0);
                    }
                    if (vouch.getSucstatus().equals("0")) {
                        AbToastUtil.showToastInThread(getApplicationContext(), "单据删除失败");
                    } else {
                        Intent intent = new Intent();
                        setResult(R.layout.layout_gcwx_lr_detail / 100000, intent);  //设置返回结果
                        finish();
                    }
                } else {
                    AbToastUtil.showToastInThread(getApplicationContext(), "单据删除失败!数据库错误");
                }
                //loadingDialog.loadingfinish();
            }

            @Override
            public void onFailure(String result) {
                //loadingDialog.loadingfinish();
                AbToastUtil.showToastInThread(getApplicationContext(), "单据删除失败!数据库错误");
            }
        });
    }

    //对一些修改后的值进行处理,避免因为没触发事件导致保存的信息不正确
    public void updatedataref() {
        if (cbxtext_et.getText() == null || cbxtext_et.getText().toString().equals("")) {
            vouch.setCbxtext("");
        } else {
            vouch.setCbxtext(cbxtext_et.getText().toString());
        }
    }

    //必输项目检查
    public boolean precheck() {
        if (vouch.getCdepcode().equals("")) {
            AbToastUtil.showToastInThread(getApplicationContext(), "维修部门必须输入!");
            return false;
        }
        if (vouch.getCdjcode().equals("")) {
            AbToastUtil.showToastInThread(getApplicationContext(), "维修等级必须输入!");
            return false;
        }
        if (vouch.getCbxtext().equals("")) {
            AbToastUtil.showToastInThread(getApplicationContext(), "维修内容必须输入!");
            return false;
        }
        if (vouch.getPrintsend().equals("") && !ismulpoint.equals("0")) {
            AbToastUtil.showToastInThread(getApplicationContext(), "维修单发送点必须输入!");
            return false;
        }
        return true;
    }

    //接收返回数据(供应商和存货明细)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case R.layout.basenvo_rchoose / 200000:
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    String cbtntype = bundle.getString("btntype");
                    String ccode = bundle.getString("ccode");
                    String cname = bundle.getString("cname");
                    if (cbtntype.equals("cdept")) {
                        cdepname_tv.setText("(" + ccode + ")" + cname);
                        cdepname_tv.setTag(ccode);
                        vouch.setCdepcode(ccode);
                        vouch.setCdepname(cname);
                    } else if (cbtntype.equals("cwxpl")) {
                        cwxplname_tv.setText("(" + ccode + ")" + cname);
                        cwxplname_tv.setTag(ccode);
                        vouch.setCwxplcode(ccode);
                        vouch.setCwxplname(cname);
                    } else if (cbtntype.equals("cwxdj")) {
                        cdjname_tv.setText("(" + ccode + ")" + cname);
                        cdjname_tv.setTag(ccode);
                        vouch.setCdjcode(ccode);
                        vouch.setCdjname(cname);
                    } else if (cbtntype.equals("printsend")) {
                        printsend_tv.setText(cname);
                        printsend_tv.setTag(ccode);
                        vouch.setPrintsend(ccode);
                        vouch.setPrintsendname(cname);
                    }
                }
                break;
            default:
                //其它窗口的回传数据
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(mFilePath); // 根据路径获取数据
                Bitmap bitmap = BitmapFactory.decodeStream(fis);
                ivShowPicture.setImageBitmap(bitmap);// 显示图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();// 关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //向左翻页
    public void btn_abs_back(View v) {
        if (icurrentrow == 0) {
            AbToastUtil.showToastInThread(getApplicationContext(), "已经是第一项");
        } else {
            insert_data(icurrentrow - 1);
        }
    }

    //向右翻页
    public void btn_abs_forward(View v) {
        if (icurrentrow == (vouchlist.size() - 1)) {
            AbToastUtil.showToastInThread(getApplicationContext(), "已经是最后一项");
        } else {
            insert_data(icurrentrow + 1);
        }
    }
}

